package org.esgl3d.ui;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

import org.esgl3d.rendering.Renderer;
import org.esgl3d.rendering.VertexContainer;
import org.esgl3d.rendering.VertexContainer.PrimitiveType;
import org.esgl3d.rendering.VertexFormat;

public class Label {
	private VertexContainer container = null;
	
	private String text = "";
	private boolean isDirty = true;
	private BitmapFont bitmapFont = null;
	private int noOfVertices;
	private int noOfTriangle;
	private int color;
	private float[] colorValuesRGBA = new float[4];
	private Renderer renderer;
	
	public Label(Renderer r) {
		renderer = r;
		container = renderer.createVertexContainer(VertexFormat.F_2Texture_2Position, 128);
	}
	
	public void setText(String value) {
		text = value;
		isDirty = true;
	}
	
	public String getText() {
		return text;
	}
	
	public void setBitmapFont(BitmapFont bitmapFont) {
		this.bitmapFont = bitmapFont;
		isDirty = true;
	}

	public BitmapFont getBitmapFont() {
		return bitmapFont;
	}
	
	//@ requires 0 <= \old(newColor);
	//@ assignable color;
	public void setColor(int newColor) {
		color = newColor;
		colorValuesRGBA[3] = (float)((newColor >> 24) & 0xff)/255;
		colorValuesRGBA[0] = (float)((newColor >> 16) & 0xff)/255;
		colorValuesRGBA[1] = (float)((newColor >> 8) & 0xff)/255;
		colorValuesRGBA[2] = (float)((newColor >> 0) & 0xff)/255;
	}
	
	public int getColor() {
		return color;
	}
	
	public void render(GL10 gl) {
		if (isDirty) {
			char[] chars = text.toCharArray();
			
			// check if new buffer size would be different to old one
			boolean bufferResize = (chars.length*2 != noOfTriangle) || (container==null);
			
			noOfTriangle = chars.length * 2;
			noOfVertices = noOfTriangle * 3;
			
			if (bufferResize) {
				/*if (container != null)
					container.release();
				
				container = renderer.createVertexContainer(VertexFormat.F_2Texture_2Position, 128);*/
			} else {
			}
					
			bitmapFont.drawInBuffers(container, chars);
			container.synchronize();

			isDirty = false;
		}
	
		bitmapFont.bindTexture(gl);
		container.draw(PrimitiveType.Triangle, 0, noOfVertices);
		
	}

}
